package com.ncu.xrpc.client;

import com.ncu.xrpc.entity.XRpcRequest;
import com.ncu.xrpc.entity.XRpcResponse;
import com.ncu.xrpc.util.HessianUtil;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.bytes.ByteArrayDecoder;
import io.netty.handler.codec.bytes.ByteArrayEncoder;
import lombok.extern.slf4j.Slf4j;

/**
 * Created by IntelliJ IDEA.
 * User: xiongwb
 * Date: 2021/9/11 20:41
 * Describe: RCP客户端（用于发送RPC请求  即：客户端的处理器）
 */
@Slf4j
public class RpcClient extends SimpleChannelInboundHandler {

    //客户端的ip
    private String ip;

    //客户端的port
    private Integer port;

    private XRpcResponse xRpcResponse;

    public RpcClient(String ip, Integer port){
        this.ip = ip;
        this.port = port;
    }

    //接收数据（基于Hessian）
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, Object msg) throws Exception {
        byte[] msg1 = (byte[]) msg;
        System.out.println("size:"+msg1.length);

        this.xRpcResponse = (XRpcResponse) HessianUtil.deserialize((byte[]) msg);

        System.out.println("++++++++++++++++++++"+this.xRpcResponse.getResult()+"---------------------");
    }

    /**
     * 出现异常的时候调用
     * @param ctx
     * @param cause
     * @throws Exception
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.error("RpcClient of exceptionCaught:",cause);
        ctx.close();
    }

    /**
     *
     * @param xRpcRequest 等待处理的请求
     * @return 处理后的响应
     */
    public XRpcResponse send(XRpcRequest xRpcRequest){
        log.info("-----------客户端 netty开始启动------------");
        NioEventLoopGroup group = new NioEventLoopGroup();
        try{
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group);
            bootstrap.channel(NioSocketChannel.class);
            bootstrap.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel socketChannel) throws Exception {
                    ChannelPipeline pipeline = socketChannel.pipeline();
                    //同样设置编码和解码器
                    pipeline.addLast(new ByteArrayEncoder());
                    pipeline.addLast(new ByteArrayDecoder());

                    //添加处理器，这里的处理器就是自己
                    pipeline.addLast(RpcClient.this);
                }
            });

            //无延时传输
            bootstrap.option(ChannelOption.TCP_NODELAY,true);

            //连接RPC服务器
            ChannelFuture futrue = bootstrap.connect(ip, port).sync();

            //拿到信道
            Channel channel = futrue.channel();

            //序列化
            byte[] serialize = HessianUtil.serialize(xRpcRequest);

            //发送
            channel.writeAndFlush(serialize).sync();

            //监听关闭
            channel.closeFuture().sync();
            return xRpcResponse;
        }catch (Exception e){
            log.error("send msg err:",e);
            e.printStackTrace();
        }finally {
            group.shutdownGracefully();
        }
        return xRpcResponse;
    }
}
